//
//  YZMSegmentForRank.m
//  YZMicroStock
//
//  Created by wangminhong on 16/5/30.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMSegmentForRank.h"
#import "UIImage+Utils.h"
#import "YZMAlertView.h"
#import "YZMRankListView.h"

@interface YZMSegmentForRank()

@property (nonatomic, strong) NSMutableArray *buttonArray;
@property (nonatomic, assign) NSInteger currentIndex;

@end

@implementation YZMSegmentForRank

- (instancetype)init{
    
    self = [super initWithFrame:CGRectMake(0, 0, 1, 1)];
    if (self) {
        
        _buttonArray = [NSMutableArray array];
        _currentIndex = -1;
        self.maxShowCount = 3;
        self.defaultIndex = 0;
    }
    return self;
}

- (void)setItemList:(NSArray *)itemList{
    
    _itemList = [NSArray arrayWithArray:itemList];
    [self redrawButtonListWithIndex:_currentIndex==-1?self.defaultIndex:_currentIndex];
}

//重绘按钮列表
- (void)redrawButtonListWithIndex:(NSInteger)index{
    
    if (!_itemList || _itemList.count == 0) {
        
        return;
    }
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [_buttonArray removeAllObjects];
    
    UIView *view = [self stackViewWithArray:_itemList andSelectedIndex:index];
    if (view) {
        
        [self addSubview:view];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.height.centerY.equalTo(self);
        }];
    }
    
    [self clickSegmentAtIndex:index];
    
}

- (UIView *)stackViewWithArray:(NSArray *)array andSelectedIndex:(NSInteger)selectedIndex{
    
    if (!array || array.count == 0) {
        
        return nil;
    }
    
    if (selectedIndex >= array.count) {
        
        return nil;
    }
    
    if (selectedIndex == 0 && array.count == 1) {
        
        //只有一个数据
        UILabel *label = [UILabel new];
        label.font = [YZMAppStyle smallSizeFont];
        label.textColor = [YZMAppStyle colorForGrayText];
        label.text = array[0];
        [_buttonArray addObject:label];
        return label;
    }
    
    UIView *stackView = [UIView new];
    
    UIView *lastView = nil;
    
    if (selectedIndex >= self.maxShowCount) {
        
        UIButton *button = [UIButton new];
        [button setBackgroundColor:[UIColor whiteColor]];
        [button setBackgroundImage:[UIImage createImageWithColor:[YZMAppStyle colorForRiseText]] forState:UIControlStateSelected];
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        button.layer.borderColor = [YZMAppStyle colorForRiseText].CGColor;
        button.layer.borderWidth = 1;
        [button setTitle:array[selectedIndex] forState:UIControlStateNormal];
        [button setTitleColor:[YZMAppStyle colorForRiseText] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [button.titleLabel setFont:[YZMAppStyle smallSizeFont]];
        [button setContentEdgeInsets:UIEdgeInsetsMake(4, 6, 4, 6)];
        button.selected = YES;
        button.userInteractionEnabled = NO;
        [stackView addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.bottom.equalTo(stackView);
        }];
        
        lastView = button;
        [_buttonArray addObject:button];
        
    }else{
        
        for (NSString *title in array) {
            
            NSInteger index = [array indexOfObject:title];
            if (index >= self.maxShowCount) {
                
                break;
            }
            
            UIButton *button = [UIButton new];
            [button setBackgroundColor:[UIColor whiteColor]];
            [button setBackgroundImage:[UIImage createImageWithColor:[YZMAppStyle colorForRiseText]] forState:UIControlStateSelected];
            button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            button.layer.borderColor = [YZMAppStyle colorForRiseText].CGColor;
            button.layer.borderWidth = 1;
            [button setTitle:title forState:UIControlStateNormal];
            [button setTitleColor:[YZMAppStyle colorForRiseText] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            [button.titleLabel setFont:[YZMAppStyle smallSizeFont]];
            [button setContentEdgeInsets:UIEdgeInsetsMake(4, 6, 4, 6)];
            [button addTarget:self action:@selector(clickSegmentButton:) forControlEvents:UIControlEventTouchUpInside];
            button.tag = index;
            [stackView addSubview:button];
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                
                if (lastView) {
                    
                    make.top.bottom.equalTo(lastView);
                    make.left.equalTo(lastView.mas_right).offset(2);
                    
                    
                }else{
                    
                    make.top.left.bottom.equalTo(stackView);
                }
            }];
            
            lastView = button;
            [_buttonArray addObject:button];
        }
    }
    
    [lastView setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
    [lastView setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    
    if (array.count > self.maxShowCount) {
        
        UIButton *button = [UIButton new];
        button.layer.borderColor = [YZMAppStyle colorForRiseText].CGColor;
        button.layer.borderWidth = 1;
        [button setImage:[UIImage imageNamed:@"icon_red_down_arrow"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(clickSegmentForMore:) forControlEvents:UIControlEventTouchUpInside];
        [stackView addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(lastView.mas_right).offset(2);
            make.top.height.equalTo(lastView);
            make.width.equalTo(lastView.mas_height);
        }];
        
        lastView = button;
    }
    
    [stackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(lastView);
    }];
    
    return stackView;
}

- (void)clickSegmentForMore:(UIButton *)sender{
    
    YZMRankListView *listView = [YZMRankListView new];
    listView.dataSource = _itemList;
    listView.clickHandle = ^(NSInteger index){
      
        if (index == _currentIndex) {
            
            return;
        }
        
        if (index >= self.maxShowCount) {
            
            if (_currentIndex >= self.maxShowCount) {
                //当前index 超出默认最多显示的个数 且选中的index 超出默认最多显示的个数时，重设按钮的内容
                UIButton *button = _buttonArray[0];
                button.tag = index;
                [button setTitle:_itemList[index] forState:UIControlStateNormal];
                [self clickSegmentAtIndex:index];
                
            }else{
                
                //重绘
                [self redrawButtonListWithIndex:index];
            }
            
        }else{
            
            if (_currentIndex >= self.maxShowCount) {
                
                //重绘
                [self redrawButtonListWithIndex:index];
                
            }else{
                
                [self clickSegmentAtIndex:index];
            }
        }
    };
    
    [listView showInView:YZMHCMInstance.currentNavationCtroller.view];
}

- (void)clickSegmentAtIndex:(NSInteger)index{
    
    _currentIndex = index;
    if (self.clickAction) {
        
        self.clickAction(_currentIndex);
    }
    
    if (_buttonArray.count >=2) {
        
        for (UIButton *instance in _buttonArray) {
            
            if (instance.tag == index) {
                
                [instance setSelected:YES];
            }else{
                
                [instance setSelected:NO];
            }
        }
    }
}

- (void)clickSegmentButton:(UIButton *)sender{
    
    _currentIndex = sender.tag;
    if (self.clickAction) {
        
        self.clickAction(_currentIndex);
    }
    
    for (UIButton *instance in _buttonArray) {
        
        if ([instance isEqual: sender]) {
            
            [instance setSelected:YES];
            
        }else{
            
            [instance setSelected:NO];
        }
    }
}

@end
